package com.module.base.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import com.module.frame.base.BaseFrameApplication;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author bsnl_yanxuwen
 */
public class FileCommonUtils {


    //单位
    public @interface ISizeUnit {
        int B = 0;
        int KB = 1;
        int MB = 2;
        int GB = 3;

    }

    /**
     * 通知图库
     */
    public static void onNotice(File filePic) {
        try {
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(filePic);
            intent.setData(uri);
            BaseFrameApplication.getContext().sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取后缀名
     */
    public static String getSuffixName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 获取文件类型
     */
    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "text/plain";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;

    }


    /**
     * 判断是否是图片
     */
    public static boolean isImageFile(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        if (options.outWidth == -1) {
            return false;
        }
        return true;
    }


    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath 文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormetFileSize(blockSize);
    }

    /**
     * 获取文件大小(不管是目录还是图片)
     */
    public static long getSize(String filePath) {
        return getSize(new File(filePath));
    }

    /**
     * 获取文件大小(不管是目录还是图片)
     */
    public static long getSize(File file) {
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return blockSize;
    }

    /**
     * 获取指定文件夹（目录）大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }

    /**
     * 获取指定文件（图片）大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists() && file.isFile()) {
            size = file.length();
        } else {
            file.createNewFile();
        }
        return size;
    }


    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = FormetFileSize(fileS,ISizeUnit.B) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = FormetFileSize(fileS,ISizeUnit.KB) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = FormetFileSize(fileS,ISizeUnit.MB) + "MB";
        } else {
            fileSizeString = FormetFileSize(fileS,ISizeUnit.GB) + "GB";
        }
        return fileSizeString;
    }

    public static double FormetFileSize(long fileS, @ISizeUnit int unit) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSize = 0;
        if (fileS == 0) {
            return fileSize;
        }
        switch (unit) {
            case ISizeUnit.B:
                fileSize = Double.parseDouble(df.format((double) fileS));
                break;
            case ISizeUnit.KB:
                fileSize = Double.parseDouble(df.format((double) fileS / 1024));
                break;
            case ISizeUnit.MB:
                fileSize = Double.parseDouble(df.format((double) fileS / 1048576));
                break;
            case ISizeUnit.GB:
                fileSize = Double.parseDouble(df.format((double) fileS / 1073741824));
                break;
        }
        return fileSize;
    }


    /**
     * 判断是否包含特殊字符
     *
     * @return false:未包含 true：包含
     */
    public static boolean inputJudge(String editText, String speChat) {
        Pattern pattern = Pattern.compile(speChat);
        Matcher matcher = pattern.matcher(editText);
        if (matcher.find()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断是否包含特殊字符
     *
     * @return false:未包含 true：包含
     */
    public static boolean inputJudge(String editText) {
        String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        return FileCommonUtils.inputJudge(editText, speChat);
    }


    /**
     * 根据路径删除指定的目录或文件，无论存在与否
     *
     * @param file 要删除的目录或文件
     * @return 删除成功返回 true，否则返回 false。
     */
    public static boolean deleteFolder(File file) {
        return deleteFolder(file.getAbsolutePath());
    }

    /**
     * 根据路径删除指定的目录或文件，无论存在与否
     *
     * @param filePath 要删除的目录或文件
     * @return 删除成功返回 true，否则返回 false。
     */
    public static boolean deleteFolder(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        } else {
            if (file.isFile()) {
                // 为文件时调用删除文件方法
                return deleteFile(filePath);
            } else {
                // 为目录时调用删除目录方法
                return deleteDirectory(filePath);
            }
        }
    }

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        return deleteDirectory(filePath, true);
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath       被删除目录的文件路径
     * @param isDelDirectory 是否删除当前目录。true，则删除子文件包含当前目录
     *                       false 则删除子文件，但是不删除当前目录，保持当前空目录
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath, boolean isDelDirectory) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return isDelDirectory ? dirFile.delete() : true;
    }


    /**
     * 重命名
     *
     * @return 返回真实路径
     */
    public static String rename(String path, String name) {
        File file = new File(path);
        String zifu = "/\\:*?<>|";
        String speChat = "[` " + zifu + " ]";
        boolean find = FileCommonUtils.inputJudge(name, speChat);
        if (find) {
            ToastUtils.showShortSafe("文件名不能包含" + zifu + "特殊字符");
            return null;
        }
        name = file.getParent() + File.separator + name;
        if (moveFile(path, name)) {
            return name;
        }
        return null;

    }


    /**
     * 移动文件
     */
    public static boolean moveFile(String oldPath$Name, String newPath$Name) {
        File oldFile = new File(oldPath$Name);
        if (!oldFile.exists()) {
            return false;
        } else if (!oldFile.isFile()) {
            return false;
        } else if (!oldFile.canRead()) {
            return false;
        }
        boolean isSuc = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                Path sourcePath = Paths.get(oldPath$Name);
                Path targetPath = Paths.get(newPath$Name);
                Files.move(sourcePath, targetPath, StandardCopyOption.ATOMIC_MOVE);
                isSuc = true;
            } catch (Exception e) {
                //当文件存在不同的文件系统，则会移到失败，所以用复制的再删除
                isSuc = copyFile(oldPath$Name, newPath$Name);
                if (isSuc) {
                    FileCommonUtils.deleteFile(oldPath$Name);
                }
            }
        } else {
            isSuc = oldFile.renameTo(new File(newPath$Name));
            if (!isSuc) {
                //当文件存在不同的文件系统，则会移到失败，所以用复制的再删除
                isSuc = copyFile(oldPath$Name, newPath$Name);
                if (isSuc) {
                    FileCommonUtils.deleteFile(oldPath$Name);
                }
            }
        }

        FileCommonUtils.onNotice(oldFile);
        FileCommonUtils.onNotice(new File(newPath$Name));
        return isSuc;
    }


    /**
     * 复制单个文件
     */
    public static boolean copyFile(String oldPath$Name, String newPath$Name) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                return false;
            } else if (!oldFile.isFile()) {
                return false;
            } else if (!oldFile.canRead()) {
                return false;
            }

            /* 如果不需要打log，可以使用下面的语句
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            */

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Path sourcePath = Paths.get(oldPath$Name);
                Path targetPath = Paths.get(newPath$Name);
                Files.copy(sourcePath, targetPath, StandardCopyOption.COPY_ATTRIBUTES);
            } else {
                FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
                byte[] buffer = new byte[1024];
                int byteRead;
                while (-1 != (byteRead = fileInputStream.read(buffer))) {
                    fileOutputStream.write(buffer, 0, byteRead);
                }
                fileInputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            return true;


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getFileName(String path) {
        if (TextUtils.isEmpty(path)) {
            return "";
        }
        try {
            String name = path.substring(path.lastIndexOf("/") + 1, path.length());
            return name;
        } catch (Exception e) {
            return "";
        }
    }

    public static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), InstallUtil.getAuthority(context), file);

        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
}
